package leetcode_acm.array;

/**
 * 功能描述
 *
 * @author: 张庭杰
 * @date: 2023年03月20日 21:05
 */
public class GenerateMatrix {

    public int[][] generateMatrix(int n) {
        if(n <= 0){
            return new int[][]{};
        }
        if(n == 1){
            return new int[][]{{1}};
        }
        int[][] ans = new int[n][n];
        int count = 1,bound = n*n+1;
        int leftBound = 0,rightBound = n-1;
        int topBound = 0,bottomBound = n-1;
        while(count != bound){
            //从左到右填充:条件,当topBound <= bottomBound的时候就可以填充
            if(topBound <= bottomBound){
                for(int i = leftBound;i<=rightBound;i++){
                    ans[topBound][i] = count++;
                }
                //当完成了本次填充,上边界向下移动
                topBound++;
            }
            //从上到下填充:条件,当leftBound <= rightBound
            if(leftBound <= rightBound){
                for(int i = topBound;i<=bottomBound;i++){
                    ans[i][rightBound] = count++;
                }
                //当完成了本次从上到下的填充,那么右边界向左移动一格
                rightBound--;
            }
            //从右到左填充:条件,当topBound <= bottomBound的时候就可以填充
            if(topBound <= bottomBound){
                for(int i = rightBound;i>=leftBound;i--){
                    ans[bottomBound][i] = count++;
                }
                //当完成了本次填充,那么下边界向上移动
                bottomBound--;
            }
            //从下到上填充:条件,当leftBound <= rightBound
            if(leftBound <= rightBound){
                for(int i = bottomBound;i>=topBound;i--){
                    ans[i][leftBound]  = count++;
                }
                //当完成了本次的填充,那么左边界向右移动
                leftBound++;
            }
        }
        return ans;
    }
}
